home *** CD-ROM | disk | FTP | other *** search
/ Tech Arsenal 1 / Tech Arsenal (Arsenal Computer).ISO / tek-01 / castools.zip / OPENPHON.C < prev    next >
Text File  |  1990-01-02  |  2KB  |  82 lines

  1.  
  2.  
  3. /*
  4.    OPENPHONE.C  Function PbOpenPhonebook:  opens an existing phonebook.
  5.  
  6.    This function opens an existing phonebook for queries or modification.
  7.  
  8.    INPUT:  Name of phonebook file, and optionally a pointer to a
  9.    phonebook structure.
  10.  
  11.    OUTPUT: If a phonebook structure was provided on input, it is filled with
  12.    the new phonebook's data.
  13. */
  14.  
  15. #include <stdlib.h>
  16. #include <malloc.h>
  17. #include <stdio.h>
  18. #include <sys\types.h>
  19. #include <sys\stat.h>
  20. #include <memory.h>
  21. #include <phonebk.h>
  22.  
  23. PB * pascal PbOpenPhonebook(PB *pb,
  24.                             char *name)
  25. {
  26.   PB *phonebook;
  27.   struct stat filestat;
  28.   size_t red;                /* for return from fread() */
  29.   int result;             /* for return from stat() */
  30.  
  31.   Pberrno = 0;            /* Initially, always reset */
  32.  
  33.   /* First, check params */
  34.   if (name == NULL) {
  35.     Pberrno = INVALIDPARAMETER;
  36.     return(NULL);
  37.   }
  38.  
  39.   /* First, check that the file named for the phonebook exists */
  40.   result = stat(name, &filestat);
  41.   if (result) {
  42.     Pberrno = FILEDOESNTEXIST;
  43.     return(NULL);
  44.   }
  45.  
  46.   /* If a phonebook structure provided, use it; otherwise allocate one */
  47.   if (!pb) {
  48.     phonebook = (PB *)malloc(sizeof(PB));
  49.     if (!phonebook) {
  50.       Pberrno = OUTOFMEM;
  51.       return(NULL);
  52.     }
  53.   }
  54.   else {
  55.     phonebook = pb;
  56.   }
  57.  
  58.   /* The file exists; open it for reading and writing, and read its header */
  59.   phonebook->fp = fopen(name, "r+b");
  60.   if (!phonebook->fp) {
  61.     Pberrno = CANTOPEN;
  62.     if (!pb) {
  63.       free(phonebook);
  64.     }
  65.     return(NULL);
  66.   }
  67.   red = fread((char *)&phonebook->header, sizeof(PBH), 1, phonebook->fp);
  68.   if (red != 1) {
  69.     Pberrno = CANTREAD;
  70.     fclose(phonebook->fp);
  71.     if (!pb) {
  72.       free(phonebook);
  73.     }
  74.     return(NULL);
  75.   }
  76.   phonebook->OBufferSize = 0;
  77.   phonebook->OBuffer = NULL;
  78.   phonebook->FirstOBufferRID = 0;
  79.  
  80.   return(phonebook);      /* And that's all! */
  81. }
  82.